<template>
  <div class="v-one-to-many-sub">
    <div class="v-one-to-many__header">
      <el-button
        icon="el-icon-close"
        type="text"
        class="v-one-to-many__action"
        style="margin-left:auto;"
        @click="handleDeleteClick"
        v-if="closable"
      />
    </div>
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" size="small">
      <el-form-item label="优惠类型" prop="rechargeDiscountType">
        <el-select
          v-model="ruleForm.rechargeDiscountType"
          placeholder="请选择优惠类型"
          class="block"
          @change="handleTypeChange"
        >
          <el-option
            v-for="(it, i) in discountCouponTypes"
            :key="i"
            :label="it.label"
            :value="it.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="基础金额" prop="rechargeDiscountBaseAmount">
        <el-input v-model="ruleForm.rechargeDiscountBaseAmount" placeholder="请输入基础金额" clearable />
      </el-form-item>

      <el-form-item label="送金额" prop="rechargeDiscountGiveAmount" v-if="isMS">
        <el-input v-model="ruleForm.rechargeDiscountGiveAmount" placeholder="请输入送金额" clearable />
      </el-form-item>

      <el-form-item label="送卷" prop="rechargeDiscountGiveCoupon" v-else>
        <TagBox closable v-model="ruleForm._rechargeDiscountGiveCoupon" :props="tagBoxProps">
          <div
            @click="openPickerTable"
            slot="footer"
            style="text-align: center;cursor: pointer;color: #1ab394;margin-left: -50px;"
          >打开列表</div>
        </TagBox>
      </el-form-item>
    </el-form>

    <Modal
      :onOk="handlePick"
      :onCancel="() => pickerModalVisible = false"
      :visible.sync="pickerModalVisible"
      :loading="pickerModalLoading"
      :width="$V.size.lg"
      appenmodelBody
      okText="选择"
      cancelText="关闭"
      title="关联"
    >
      <Picker ref="tmp" crossPick :lastPicked="ruleForm._rechargeDiscountGiveCoupon" />
    </Modal>
  </div>
</template>
<script>
import { Emitter, Form } from '@/mixins'
import { rechargeSubModel } from '../model'
import { discountCouponEnum } from '@/core/enum'
import rule from '@/utils/rule'
import TagBox from '@/components/tag-box/TagBox'
import Picker from './CouponPicker'

export default {
  componentName: 'RechargeSubForm',
  mixins: [Form('ruleForm', rechargeSubModel), Emitter],
  components: { TagBox, Picker },
  props: {
    uuid: [String, Number],
    closable: {
      type: Boolean,
      default: true
    },
    record: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  data () {
    return {
      // -------- Picker ----------
      pickerModalVisible: false,
      pickerModalLoading: false,
      pickerType: '',
      // -------- !Picker ----------
      tagBoxProps: { value: 'couponId', label: 'couponName' },

      ruleForm: this.initDefaults({
        rechargeDiscountType: discountCouponEnum.ms
      }),
      rules: {
        rechargeDiscountBaseAmount: [
          {
            required: true,
            message: this.$t('required', { field: '基础金额' })
          },
          {
            pattern: rule.positiveDecimalRegex,
            message: this.$t('only accept postive decima')
          }
        ],
        rechargeDiscountGiveAmount: [
          {
            required: true,
            message: this.$t('required', { field: '送金额' })
          },
          {
            pattern: rule.positiveDecimalRegex,
            message: this.$t('only accept postive decima')
          }
        ],
        rechargeDiscountGiveCoupon: [
          {
            required: false,
            message: this.$t('required', { field: '送卷' })
          }
        ]
      }
    }
  },

  created () {
    this.dispatch('RechargeForm', 'subform.created', [this])

    this.$on('subform.initialize', this.initialize)
  },

  destroyed () {
    this.dispatch('RechargeForm', 'subform.destroyed', [this])
  },

  computed: {
    pickPrimaryKey () {
      return this.tagBoxProps['value']
    },
    isMS: {
      get () {
        return this.ruleForm.rechargeDiscountType === discountCouponEnum.ms
      },
      set (val) {
        if (val) {
          this.rules.rechargeDiscountGiveAmount[0].required = true
          this.rules.rechargeDiscountGiveCoupon[0].required = false
          this.$refs.ruleForm.validateField('rechargeDiscountGiveCoupon')
        } else {
          this.rules.rechargeDiscountGiveAmount[0].required = false
          this.rules.rechargeDiscountGiveCoupon[0].required = true
          this.$refs.ruleForm.validateField('rechargeDiscountGiveAmount')
        }
      }
    },
    discountCouponTypes () {
      return this.$mapEnumToSelect(discountCouponEnum, {
        valueTransfer: null,
        keyFilter: (key) => !/^ms|msj$/.test(key)
      })
    }
  },

  methods: {
    initialize ({ uuid, data }) {
      if (this.uuid === uuid) {
        this.ruleForm = data
      }
    },
    handleDeleteClick () {
      this.dispatch('RechargeForm', 'subform.removed', this)
    },
    submit (callback) {
      this.$refs.ruleForm.validate((valid) => {
        callback(valid, this.ruleForm)
      })
    },
    resetForm () {
      this.$refs.ruleForm.resetFields()
    },

    handleTypeChange (val) {
      this.isMS = val === discountCouponEnum.ms
    },

    // ------------------------------ picker 开始 ------------------------------
    getSelection () {
      let selected = this.$refs.tmp.getSelection()

      return selected
    },

    handlePick () {
      try {
        this.$refs.tmp.assertSelection()

        const selects = this.getSelection()
        this.ruleForm._rechargeDiscountGiveCoupon = selects
        this.pickerModalVisible = false
      } catch (err) {
        this.$message.warning(err.message)
      }
    },
    openPickerTable () {
      this.pickerModalVisible = true
    }
    // ------------------------------ picker 结束 ------------------------------
  },
  mounted () {
    this.watchSelect(
      'rechargeDiscountType',
      'rechargeDiscountTypeValue',
      this.discountCouponTypes
    )
    this.$watch(
      'ruleForm._rechargeDiscountGiveCoupon',
      (val) => {
        if (val && val.length) {
          this.ruleForm.rechargeDiscountGiveCoupon = val
            .map((it) => it[this.pickPrimaryKey])
            .join(',')
        }
      },
      {
        immediate: true
      }
    )
  }
}
</script>
